package cn.xiaopengstack.domain.weixin.auth.service;

import cn.xiaopengstack.api.service.ILoginService;
import cn.xiaopengstack.domain.weixin.auth.adapter.ILoginPort;
import com.google.common.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author jiangyangang
 */
@Service
@Slf4j
public class WeixinLoginService implements ILoginService {

    @Resource
    private ILoginPort loginPort;
    @Resource
    private Cache<String, String> openidToken;

    private static final String CACHE_TICKET_OPEN_ID = "cache:wenxin:auth:%s";

    @Override
    public void saveLoginState(String ticket, String openid) throws IOException {
        openidToken.put(String.format(CACHE_TICKET_OPEN_ID, ticket), openid);
        loginPort.sendLoginTemplate(openid);
    }

    @Override
    public String createQrCodeTicket() throws IOException {
        return loginPort.createQrCodeTicket();
    }

    @Override
    public String checkLogin(String ticket) {
        return openidToken.getIfPresent(String.format(CACHE_TICKET_OPEN_ID, ticket));
    }
}
